package com.kexun;

import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.kexun.common.xss.XssFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.Arrays;

@SpringBootApplication
@EnableScheduling
@EnableAsync
@EnableCaching
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 259200)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.profiles", name = "active", havingValue = "prop")
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public ServletRegistrationBean kaptchaServlet() {
        ServletRegistrationBean servlet = new ServletRegistrationBean(new KaptchaServlet(), "/kaptcha.jpg");
        servlet.addInitParameter(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_CONFIG_KEY, com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        servlet.addInitParameter(com.google.code.kaptcha.Constants.KAPTCHA_IMAGE_HEIGHT, "60");
        servlet.addInitParameter(com.google.code.kaptcha.Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "50");
        servlet.addInitParameter(com.google.code.kaptcha.Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
        return servlet;
    }

    @Bean
    public FilterRegistrationBean timerFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new XssFilter());
        filterRegistrationBean.addInitParameter("excludedPages", "/add/app");
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        return filterRegistrationBean;
    }

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setThreadNamePrefix("time-task-");
        taskScheduler.setPoolSize(30);
        taskScheduler.initialize();
        return taskScheduler;
    }
}
